#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <chrono>

#define MAX_SIZE 100

typedef struct {
    int k;
    int tid;
    double (*A)[MAX_SIZE];
    int n;
} ThreadParam_t;

void *eliminate(void *arg) {
    ThreadParam_t *param = (ThreadParam_t *)arg;
    int k = param->k;
    int tid = param->tid;
    double (*A)[MAX_SIZE] = param->A;
    int n = param->n;

    for (int j = k + 1 + tid; j < n; j += n - 1) {
        A[k][j] = A[k][j] / A[k][k];
    }
    A[k][k] = 1.0;

    return NULL;
}

int main() {
    int n; // Assuming n is defined somewhere
    double A[MAX_SIZE][MAX_SIZE]; // Assuming A is defined somewhere

    auto start = std::chrono::high_resolution_clock::now();

    for (int k = 0; k < n; ++k) {
        // 主线程做除法操作
        for (int j = k + 1; j < n; j++) {
            A[k][j] = A[k][j] / A[k][k];
        }
        A[k][k] = 1.0;

        // 创建工作线程，进行消去操作
        int worker_count = n - 1 - k;
        pthread_t *handles = (pthread_t *)malloc(worker_count * sizeof(pthread_t));
        ThreadParam_t *param = (ThreadParam_t *)malloc(worker_count * sizeof(ThreadParam_t));

        // 分配任务
        for (int tid = 0; tid < worker_count; tid++) {
            param[tid].k = k;
            param[tid].tid = tid;
            param[tid].A = A;
            param[tid].n = n;
        }

        // 创建线程
        for (int tid = 0; tid < worker_count; tid++) {
            pthread_create(&handles[tid], NULL, eliminate, &param[tid]);
        }

        // 主线程挂起等待所有的工作线程完成此轮消去工作
        for (int tid = 0; tid < worker_count; tid++) {
            pthread_join(handles[tid], NULL);
        }

        free(handles);
        free(param);
    }

    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    printf("Program execution time: %lld ms\n", duration);

    return 0;
}
